package com.mililoan.service.module.system.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mililoan.common.bean.PageResultSet;
import com.mililoan.model.system.Actor;
import com.mililoan.model.system.Function;
import com.mililoan.model.system.User;
import com.mililoan.persist.system.ActorDao;
import com.mililoan.persist.system.ActorRightDao;
import com.mililoan.persist.system.UserDao;
import com.mililoan.persist.system.UserRightDao;
import com.mililoan.service.module.system.UserBo;

/**
 * 用户控制类实现类
 * 
 * @author mwei
 *
 */
@Service("UserBo")
public class UserBoImpl implements UserBo {
	@Autowired
	private UserDao userDao;
	@Autowired
	private ActorDao actorDao;
	@Autowired
	private UserRightDao userRightDao;
	@Autowired
	private ActorRightDao actorRightDao;
//	@Resource(name = "departmentDao")
//	private DepartmentDao	departmentDao;

	/**
	 * 查询用户
	 * 
	 * @param user,page,pageSize
	 * @return 用户ID
	 * @author mwei
	 */
	@SuppressWarnings("unchecked")
	public PageResultSet<User> query(User user, int page, int pageSize) {
		PageResultSet<User> prs = userDao.query(user, page, pageSize);
//		List<User> list = prs.getResult();
//		for (int i = 0; i < list.size(); i++) {
//			User temUser = list.get(i);
//			temUser.setActors(userRightDao.getActorsById(temUser.getId()));
//			String stringActorNames = "";
//			for (int k = 0; k < temUser.getActorNames().size(); k++) {
//				if (k != 0)
//					stringActorNames += "<br/>";
//				stringActorNames += temUser.getActorNames().get(k);
//			}
//			temUser.setStringActorNames(stringActorNames);
//		}
		return prs;
	}

	/**
	 * 查询所有用户
	 * 
	 * @param user,page,pageSize
	 * @return 用户ID
	 * @author mwei
	 */
	public ArrayList<User> queryAll(User user) {
		return userDao.queryAll(user);
	}

	/**
	 * 添加用户
	 * 
	 * @param user
	 * @return 用户ID
	 * @author mwei
	 * @throws Exception
	 */
	public Long addUser(User user) throws Exception {
		Long newId = userDao.addUser(user);
//		Actor defaultActor = actorDao.getDefaultDepartmentActo(user.getDepartmentCode());
		// 添加默认角色
//		if (null != newId && null != defaultActor && defaultActor.getId() != null) {
//			if (userRightDao.addUserActor(newId, defaultActor.getId())) {
//				return newId;
//			}
//		}
		return newId;
	}

	/**
	 * 修改用户
	 * 
	 * @param user
	 * @return 用户ID
	 * @author mwei
	 * @throws Exception
	 */
	public Long updateUser(User user) throws Exception {
		User oldUser = userDao.getUser(user.getId());
		Long userId = userDao.updateUser(user);
		if (null != userId) {
			// 修改密码
			if (StringUtils.isNotEmpty(user.getUserPwd()) && !user.getUserPwd().equals(oldUser.getUserPwd())) {
				userDao.updatePassword(userId, user.getUserPwd());
			}
			// 修改部门时修改角色
/*			if (null != user.getDepartmentCode()
					&& (user.getDepartmentCode().intValue() != oldUser.getDepartmentCode().intValue())) {

				userRightDao.delUserActor(userId);
				Actor defaultActor = actorDao.getDefaultDepartmentActo(user.getDepartmentCode());
				userRightDao.addUserActor(userId, defaultActor.getId());
			}*/
		}
		return userId;
	}

	/**
	 * 修改用户的角色和功能
	 * 
	 * @param user
	 * @return boolean
	 * @author mwei
	 * @throws Exception
	 */
	public boolean updateActor(User user) throws Exception {
		// 删除原有的角色和功能
		boolean flag = true;
		if (null != user) {
			flag = userRightDao.delUserActor(user.getId());
			if (flag && null != user.getActorCodes()) {
				flag = userRightDao.addUserActor(user.getId(), user.getActorCodes());
			}
			if (flag && null != user.getFunCodes()) {
				flag = userRightDao.addUserFun(user.getId(), user.getFunCodes());
			}
		}
		return flag;
	}

	/**
	 * 验证互斥权限（按模块）
	 * 
	 * @param actorsList
	 * @param funsList
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public boolean checkFuns(ArrayList actorsList, ArrayList funsList) {
		List allFuns = new ArrayList();
		if (null != actorsList) {
			for (int i = 0; i < actorsList.size(); i++) {
				Integer actorid = (Integer) (actorsList.get(i));

				List tempList = actorRightDao.getActorRight(actorid);
				for (int j = 0; j < tempList.size(); j++) {
					Function ff = (Function) tempList.get(j);
					allFuns.add(ff.getCode());
				}
			}
		}
		if (null != funsList) {
			for (int i = 0; i < funsList.size(); i++) {
				Integer funid = (Integer) (funsList.get(i));
				allFuns.add(funid);
			}
		}

		String rowa = "[1],[2]"; // 系统管理
		String rowb = "[3]"; // 审计
		String rowc = "[4]"; // 征信
		int flaga = 0;
		int flagb = 0;
		int flagc = 0;
		for (int i = 0; i < allFuns.size(); i++) {
			Integer funid = (Integer) (allFuns.get(i));
			String topNum = null;
			if (funid < 1000)
				topNum = funid.toString().substring(0, 1);
			else
				topNum = funid.toString().substring(0, 2);

			// System.out.println(funid+ "#" +topNum);
			if (rowa.indexOf("[" + topNum + "]") >= 0) {
				flaga = 1;
			}
			if (rowb.indexOf("[" + topNum + "]") >= 0) {
				flagb = 1;
			}
			if (rowc.indexOf("[" + topNum + "]") >= 0) {
				flagc = 1;
			}
		}
		if (flaga + flagb + flagc > 1) {
			return false;
		} else {
			return true;
		}

	}

	/**
	 * 修改密码
	 * 
	 * @param userId,password
	 * @return 用户ID
	 * @author mwei
	 */
	public Long updatePassword(Long userId, String password) {
		return userDao.updatePassword(userId, password);
	}

	/**
	 * 删除用户
	 * 
	 * @param userId
	 * @return 用户ID
	 * @author mwei
	 */
	public Long delUser(Long userId) {
		return userDao.delUser(userId);
	}

	/**
	 * 根据用户名和密码获得用户信息
	 * 
	 * @param accounts
	 * @param password
	 * @return user 如果没有记录返回NULL
	 * @author mwei
	 */
	public User getUser(String accounts, String password) {
		User user = userDao.getUser(accounts, password);
		if (null != user) {
			ArrayList<Actor> actors = userRightDao.getActorsById(user.getId());
			if (null != actors) {
				for (int i = 0; i < actors.size(); i++) {
					Actor temActor = actors.get(i);
					temActor.setFuncs(actorRightDao.getActorRight(temActor.getId()));
				}
			}
			user.setActors(actors);
			user.setFuncs(userRightDao.getFuncsById(user.getId()));
		}
		return user;
	}

	/**
	 * 根据用户名帐号得用户信息
	 * 
	 * @param accounts
	 * @return user 如果没有记录返回NULL
	 * @author mwei
	 */
	public User getUser(String accounts) {
		User user = userDao.getUser(accounts);
		if (null != user) {
			ArrayList<Actor> actors = userRightDao.getActorsById(user.getId());
			if (null != actors) {
				for (int i = 0; i < actors.size(); i++) {
					Actor temActor = actors.get(i);
					temActor.setFuncs(actorRightDao.getActorRight(temActor.getId()));
				}
			}
			user.setActors(actors);
			user.setFuncs(userRightDao.getFuncsById(user.getId()));
		}
		return user;
	}

	/**
	 * 根据用户名ID得用户信息
	 * 
	 * @param id
	 * @return user 如果没有记录返回NULL
	 * @author mwei
	 */
	public User getUserById(Long id) {
		return userDao.getUser(id);
	}

	/**
	 * 根据用户名ID得带权限的用户信息
	 * 
	 * @param id
	 * @return user 如果没有记录返回NULL
	 * @author
	 */
	public User getUserWithActor(Long id) {
		User user = userDao.getUser(id);
		if (null != user) {
			ArrayList<Actor> actors = userRightDao.getActorsById(user.getId());
			if (null != actors) {
				for (int i = 0; i < actors.size(); i++) {
					Actor temActor = actors.get(i);
					temActor.setFuncs(actorRightDao.getActorRight(temActor.getId()));
				}
			}
			user.setActors(actors);
			user.setFuncs(userRightDao.getFuncsById(user.getId()));
			//user.setBuildings(userRightDao.getRefid(user.getId(), 9900));
		}
		return user;
	}

	/**
	 * 根据用户权限
	 * 
	 * @param user
	 * @return HashSet<Integer>
	 * @author mwei
	 */
	public HashSet<Integer> getUserActor(User user) {
		HashSet<Integer> actSet = new HashSet<Integer>();
		ArrayList<Actor> actors = user.getActors();
		for (int i = 0; i < actors.size(); i++) {
			ArrayList<Function> actFuns = actors.get(i).getFuncs();
			for (int j = 0; j < actFuns.size(); j++) {
				if (actFuns.get(j).getFlag().equalsIgnoreCase("1"))
					actSet.add(actFuns.get(j).getCode());
			}
		}
		for (int i = 0; i < actors.size(); i++) {
			ArrayList<Function> actFuns = actors.get(i).getFuncs();
			for (int j = 0; j < actFuns.size(); j++) {
				if (actFuns.get(j).getFlag().equalsIgnoreCase("0"))
					actSet.remove(actFuns.get(j).getCode());
			}
		}
		ArrayList<Function> funs = user.getFuncs();
		for (int i = 0; i < funs.size(); i++) {
			if (funs.get(i).getFlag().equalsIgnoreCase("1"))
				actSet.add(funs.get(i).getCode());
		}
		for (int i = 0; i < funs.size(); i++) {
			if (funs.get(i).getFlag().equalsIgnoreCase("0"))
				actSet.remove(funs.get(i).getCode());
		}
		return actSet;
	}

	public ArrayList<User> queryAllExc(User user) {
		return userDao.queryAllExc(user);
	}
}
